//首页列表样式小部件
// ignore: must_be_immutable
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:oktoast/oktoast.dart';
import 'package:ycbl/config/bl_color.dart';
import 'package:ycbl/ext/common_ext.dart';
import 'package:ycbl/config/bl_style.dart';
import 'package:ycbl/config/route_manager.dart';
import 'package:ycbl/utils/log_util.dart';
import 'package:ycbl/utils/user_config.dart';
import 'package:ycbl/widget/image.dart';

import 'bl_round_avatar.dart';
import 'bl_shadow_layout.dart';
import 'border_label.dart';

class ProductItemCell extends StatefulWidget {
  var productCourse; //科目：语文、数学、物理等
  var productName; //课程名称
  var startDate; //开始日期
  var endDate; //结束日期
  var rnNumber; //共多少节课，暂无
  var teacherHead; //教师头像mongodbid
  var teacherName; //教师名字
  var nowNumber; //报名人数
  var userIds; //报名的学生id
  var productNowPrice; //当前价格
  var productOldPrice; //以前价格
  Map<String, dynamic> allItemData; //所有字段的信息
  //构造方法
  ProductItemCell(
      {Key key,
      this.productCourse,
      this.productName,
      this.startDate,
      this.endDate,
      this.rnNumber,
      this.teacherHead,
      this.teacherName,
      this.nowNumber,
      this.userIds,
      this.productNowPrice,
      this.productOldPrice,
      this.allItemData})
      : super(key: key);

  @override
  _ProductItemCellState createState() => _ProductItemCellState(
      productCourse: productCourse,
      productName: productName,
      startDate: startDate,
      endDate: endDate,
      rnNumber: rnNumber,
      teacherHead: teacherHead,
      teacherName: teacherName,
      nowNumber: nowNumber,
      userIds: userIds,
      productNowPrice: productNowPrice,
      productOldPrice: productOldPrice,
      allItemData: allItemData);
}

class _ProductItemCellState extends State<ProductItemCell> {
  var productCourse; //科目：语文、数学、物理等
  var productName; //课程名称
  var startDate; //开始日期
  var endDate; //结束日期
  var rnNumber; //共多少节课，暂无
  var teacherHead; //教师头像mongodbid
  var teacherName; //教师名字
  var nowNumber; //报名人数
  var userIds; //报名的学生id
  var productNowPrice; //当前价格
  var productOldPrice; //以前价格
  Map<String, dynamic> allItemData; //所有字段的信息

  //更新字段信息
  String userId = "";
  bool isBuy = false;
  bool isFree = false;
  bool isOnePrice = true;
  String textStr = "";

  //构造方法
  _ProductItemCellState(
      {Key key,
      this.productCourse,
      this.productName,
      this.startDate,
      this.endDate,
      this.rnNumber,
      this.teacherHead,
      this.teacherName,
      this.nowNumber,
      this.userIds,
      this.productNowPrice,
      this.productOldPrice,
      this.allItemData});

  _baoMingSubmit(var courseId) async {
    if (UserConfig.instance.getUserId() == null) {
      Navigator.push(
          context,
          BLRouter.generateRoute(
              new RouteSettings(name: BLRouteName.login_code)));
    }else{
      LogUtil.e("提交免费报名的 courseId    $courseId");
      var apiUrl = "https://ycsc.bailiedu.cn/add_addInfo.do?";
      Dio dio = new Dio();
      Response response = await dio.get(apiUrl +
          "tableId=435&pageId=2895&source=1&isInterFace=1&STU_ID=${UserConfig.instance.getUserId()}&IF_APPAY=0&ORDER_PRODUCT=1&ORDER_PRODUCT_ID=$courseId&CART_IDS=&SUMMONEY=0&MAXNOWUSESALEMONEY=&OS_SALE_MONEY=&SOURCE_MONEY=&TOTAL_MONEY=0&ADDRESS=&BUY_NUM=1&ZD_PRICE_TYPE=1&ZH_COURSE_ID=0&ZH_GRADE_ID=0&seatFlag=0&ZD_DD_ZT=1&ORDER_SOURCE=792&SALE_ARR=0&SALE_ARR_ID=&SALE_TYPE=&SALE_MONEY=&SALE_YEAR=&SALE_JD=&SALE_NJ=&SEAT_ID=&ZD_HDJ_DATE=");
      print("立即报名接口数据结果：");
      print(response.data);
      String successCode = response.data;
      LogUtil.e(successCode);
      if (successCode != '0') {
        showToast("报名成功！");
        setState(() {
          isBuy = true;
          nowNumber++;
        });
      }
    }

  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    //判断是否包含用户id
    userId = UserConfig.instance.getUserId().toString();
    List<String> userIdsArr = userIds.toString().split(",");
    isBuy = (userId == null || userId == "null")
        ? false
        : userIdsArr.contains(userId);

    LogUtil.e("item isBuy   $isBuy");
    //判断是否免费
    isFree = (productNowPrice == 0);
    LogUtil.e("item isFree   $isFree");

    isOnePrice = (productNowPrice == productOldPrice);

    //关键代码

    if (startDate == null) {
      startDate = 1;
    }
    if (endDate == null) {
      endDate = 2;
    }
    if (rnNumber == null) {
      rnNumber = 3;
    }
    textStr = "$startDate - $endDate 共$rnNumber节课";
  }

  @override
  Widget build(BuildContext context) {
    _onClick() {
      Navigator.push(
          context,
          BLRouter.generateRoute(new RouteSettings(
              name: BLRouteName.courseDetail, arguments: allItemData)));
    }

    var card = new Padding(
      padding: EdgeInsets.fromLTRB(16, 8, 16, 8),
      child: BLShadowLayout(
        child: Container(
          color: BLColor.whiteColor,
          padding:
              EdgeInsets.only(left: 16.0, top: 16.5, right: 16.0, bottom: 18.0),
          child: new Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  BorderLabel(
                    text: productCourse ?? '未知',
                  ),
                  SizedBox(
                    width: 5,
                  ),
                  Expanded(
                    child: Text(
                      productName,
                      style: BLStyle.commonBlackTextStyle.wrapHeight(),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  )
                ],
              ),
              // 上课日期 + 课时 行
              Padding(
                padding: EdgeInsets.only(top: 10, bottom: 10),
                child: Text(
                  textStr,
                  style: BLStyle.smallTextStyle.wrapHeight(),
                ),
              ),
              Container(
                child: Row(
                  //左右布局分别显示：左侧为教师和多少人报名，右侧为价格区域
                  children: <Widget>[
                    Expanded(
                      flex: 2,
                      //左侧教师和多少人报名
                      child: Container(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Row(
                              children: [
                                BLRoundAvatar(
                                  size: 30,
                                  borderColor: BLColor.whiteColor,
                                  url: teacherHead,
                                ),
                                SizedBox(
                                  width: 5,
                                ),
                                Text(
                                  teacherName ?? "教师",
                                  style: BLStyle.smallTextStyle,
                                ),
                              ],
                            ),
                            //间距
                            SizedBox(
                              height: 10,
                            ),
                            // 报名人数 行
                            Text(
                              nowNumber == null ? '已报名' : '$nowNumber人已报名',
                              style: BLStyle.smallGreyTextStyle,
                            ),
                          ],
                        ),
                      ),
                    ),
                    isBuy
                        ? Column(
                      children: <Widget>[
                        Container(
                          height: 28.0,
                          child: RaisedButton(
                            elevation: 0.0,
                            clipBehavior: Clip.hardEdge,
                            shape: RoundedRectangleBorder(
                                side: BorderSide(
                                  color: Color(0xffF0F0F0),
                                ),
                                borderRadius: BorderRadius.all(
                                    Radius.circular(14.0))),
                            color: Color(0xffFEEDE4),
                            onPressed: () {
                              //跳转页面
                              _onClick();
                            },
                            child: Text(
                              "已报名",
                              style: TextStyle(
                                  fontSize: 14.0,
                                  color: Color(0xff999999)),
                            ),
                          ),
                        ),
                      ],
                    )
                        : isFree
                        ?   Align(
                      child: Container(
                        height: 28.0,
                        child: RaisedButton(
                          elevation: 0.0,
                          clipBehavior: Clip.hardEdge,
                          shape: RoundedRectangleBorder(
                              side: BorderSide(
                                color: Color(0xffFF3C00),
                              ),
                              borderRadius: BorderRadius.all(
                                  Radius.circular(14.0))),
                          color: Color(0xffFF3C00),
                          onPressed: () {
                            //跳转页面
                            _baoMingSubmit(
                                "${allItemData['COURSEID']}");
                          },
                          child: Text(
                            "免费报名",
                            style: TextStyle(
                                fontSize: 14.0,
                                color: Color(0xffFFFFFF)),
                          ),
                        ),
                      ),
                    )
                        : isOnePrice
                        ? Column(
                      mainAxisAlignment:
                      MainAxisAlignment.end,
                      crossAxisAlignment:
                      CrossAxisAlignment.end,
                      children: <Widget>[
                        Container(
                          margin: const EdgeInsets.only(
                              left: 0,
                              right: 10,
                              top: 3,
                              bottom: 0),
                          child: new Text("￥$productNowPrice",
                              style: TextStyle(
                                color: Colors.red,
                                fontSize: 15.0,
                              )),
                        ),
                      ],
                    )
                        : Column(
                      mainAxisAlignment:
                      MainAxisAlignment.end,
                      crossAxisAlignment:
                      CrossAxisAlignment.end,
                      children: <Widget>[
                        Container(
                          margin: const EdgeInsets.only(
                              left: 0,
                              right: 10,
                              top: 0,
                              bottom: 0),
                          child: new Text(
                            "￥$productOldPrice",
                            style: TextStyle(
                              color: Colors.grey,
                              decoration:
                              TextDecoration.lineThrough,
                              decorationColor: Colors.grey,
                              fontSize: 10.0,
                            ),
                          ),
                        ),
                        Container(
                          margin: const EdgeInsets.only(
                              left: 0,
                              right: 10,
                              top: 3,
                              bottom: 0),
                          child: new Text("￥$productNowPrice",
                              style: TextStyle(
                                color: Colors.red,
                                fontSize: 15.0,
                              )),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );

    return Container(child: GestureDetector(onTap: _onClick, child: card));
  }
}

class ProductItemData {
  var productCourse; //科目：语文、数学、物理等
  var productName; //课程名称
  var startDate; //开始日期
  var endDate; //结束日期
  var rnNumber; //共多少节课，暂无
  var teacherHead; //教师头像mongodbid
  var teacherName; //教师名字
  var nowNumber; //报名人数
  var userIds; //报名的学生id
  var productNowPrice; //当前价格
  var productOldPrice; //现价
  Map<String, dynamic> allItemData;

  ProductItemData(
      {this.productCourse,
      this.productName,
      this.startDate,
      this.endDate,
      this.rnNumber,
      this.teacherHead,
      this.teacherName,
      this.nowNumber,
      this.userIds,
      this.productNowPrice,
      this.productOldPrice,
      this.allItemData});

  factory ProductItemData.formJson(Map json) {
    return ProductItemData(
        productCourse: json['PRODUCT_COURSE'],
        productName: json['PRODUCT_NAME'],
        startDate: json['START_DATE'],
        endDate: json['END_DATE'],
        rnNumber: json['COURSE_NUM'],
        teacherHead: json['TEA_MONGODB_ID'],
        teacherName: json['TEACHERNAME'],
        nowNumber: json['APPLY_NUM'],
        userIds: json['USERIDS'],
        productOldPrice: json['PRODUCT_OLD_PRICE'],
        productNowPrice: json['PRODUCT_NOW_PRICE'],
        allItemData: json);
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['PRODUCT_COURSE'] = this.productCourse;
    data['PRODUCT_NAME'] = this.productName;
    data['START_DATE'] = this.startDate;
    data['END_DATE'] = this.endDate;
    data['COURSE_NUM'] = this.rnNumber;
    data['TEA_MONGODB_ID'] = this.teacherHead;
    data['TEACHERNAME'] = this.teacherName;
    data['APPLY_NUM'] = this.nowNumber;
    data['USERIDS'] = this.userIds;
    data['PRODUCT_OLD_PRICE'] = this.productOldPrice;
    data['PRODUCT_NOW_PRICE'] = this.productNowPrice;
    data['ALL_ITEM_DATA'] = this.allItemData;
    return data;
  }
}
